package TicketingSystem;

import connection.Conn;
import Frame.MyFrame;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Login {
    private static JTextField userField;
    private static JPasswordField passField;
    private static int loggedInUserID;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> createLoginFrame());
    }
    // 登录界面
    public static void createLoginFrame() {
        MyFrame frame = new MyFrame("电影票务管理系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout(5, 5));

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("电影票务管理系统");
        titleLabel.setFont(new Font("隶书", Font.BOLD, 50));
        titlePanel.add(titleLabel);

        // 用户名输入
        JPanel userPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        JLabel userLabel = new JLabel("用户名：");
        userLabel.setFont(new Font("楷书", Font.PLAIN, 24));
        userField = new JTextField();
        userField.setPreferredSize(new Dimension(200, 30));
        userPanel.add(userLabel);
        userPanel.add(userField);

        // 密码输入
        JPanel passPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        JLabel passLabel = new JLabel("密　码：");
        passLabel.setFont(new Font("楷书", Font.PLAIN, 24));
        passField = new JPasswordField();
        passField.setPreferredSize(new Dimension(200, 30));
        passPanel.add(passLabel);
        passPanel.add(passField);

        // 注册登录按钮
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton loginBtn = new JButton("登录");
        loginBtn.setFont(new Font("楷书", Font.PLAIN, 24));
        JButton registerBtn = new JButton("注册");
        registerBtn.setFont(new Font("楷书", Font.PLAIN, 24));
        loginBtn.setPreferredSize(new Dimension(115, 40));
        registerBtn.setPreferredSize(new Dimension(115, 40));
        btnPanel.add(loginBtn);
        btnPanel.add(registerBtn);

        // 修改密码
        JPanel changepwdPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton changepwdBtn = new JButton("修改密码");
        changepwdBtn.setFont(new Font("楷书", Font.PLAIN, 24));
        changepwdBtn.setPreferredSize(new Dimension(250, 40));
        changepwdPanel.add(changepwdBtn);

        // 注册按钮点击事件
        registerBtn.addActionListener(e -> new RegistrationFrame());

        // 修改密码按钮点击事件
        changepwdBtn.addActionListener(e -> new ChangePasswordFrame());

        // 登录按钮点击事件
        loginBtn.addActionListener(e -> {
            String username = userField.getText();
            String password = passField.getText();

            // 先尝试以管理员身份登录
            int adminUserID = UserService.login(username, password, true);
            if (adminUserID != -1) {
                // 管理员登录成功的逻辑不变
                JOptionPane.showMessageDialog(frame, "管理员登录成功！");
                // 创建管理员主界面
                MyFrame adminFrame = new MyFrame("管理员后台");
                adminFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                adminFrame.setLayout(new BorderLayout(5, 5));

                // 创建侧边栏面板
                JPanel sidebarPanel = new JPanel();
                sidebarPanel.setLayout(new BoxLayout(sidebarPanel, BoxLayout.Y_AXIS));
                sidebarPanel.setBackground(new Color(0, 150, 200));

                // 使用 CardLayout 管理功能界面
                JPanel functionContainer = new JPanel(new CardLayout());
                functionContainer.setBackground(new Color(240, 248, 255));
                adminFrame.add(functionContainer, BorderLayout.CENTER);

                // 添加管理员功能按钮
                String[] adminOptions = {"场地管理", "用户管理","电影票管理", "活动门票管理", "退出登录"};
                for (String option : adminOptions) {
                    JButton optionButton = new JButton(option);
                    optionButton.setFont(new Font("楷体", Font.BOLD, 20));
                    optionButton.setBackground(new Color(0, 150, 200));
                    optionButton.setBorderPainted(false);
                    optionButton.setFocusPainted(false);
                    optionButton.setContentAreaFilled(false);
                    optionButton.setOpaque(true);

                    if ("场地管理".equals(option)) {
                        // 场地管理点击弹出菜单
                        optionButton.addActionListener(e3 -> {
                            // 创建场地管理弹出菜单
                            JPopupMenu popupMenu = new JPopupMenu();

                            // 创建场地管理子选项
                            JMenuItem venueBookingItem = new JMenuItem("场地预定");
                            JMenuItem venueManagementItem = new JMenuItem("场地管理");

                            // 设置子选项样式与主按钮一致
                            venueBookingItem.setFont(new Font("楷体", Font.BOLD, 20));
                            venueBookingItem.setBackground(new Color(240, 248, 255));
                            venueBookingItem.setBorderPainted(false);
                            venueBookingItem.setFocusPainted(false);
                            venueBookingItem.setContentAreaFilled(false);
                            venueBookingItem.setOpaque(true);

                            venueManagementItem.setFont(new Font("楷体", Font.BOLD, 20));
                            venueManagementItem.setBackground(new Color(240, 248, 255));
                            venueManagementItem.setBorderPainted(false);
                            venueManagementItem.setFocusPainted(false);
                            venueManagementItem.setContentAreaFilled(false);
                            venueManagementItem.setOpaque(true);

                            // 添加子选项到弹出菜单
                            popupMenu.add(venueBookingItem);
                            popupMenu.add(venueManagementItem);

                            // 显示弹出菜单
                            popupMenu.show(optionButton, optionButton.getWidth(), 0);

                            // 场地预定的点击事件
                            venueBookingItem.addActionListener(e1 -> {
                                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                functionContainer.removeAll();
                                TicketingService ticketingService = new TicketingService();
                                JPanel venueBookingPanel = createVenueBookingPanel(ticketingService);
                                functionContainer.add(venueBookingPanel, "场地预定");
                                cardLayout.show(functionContainer, "场地预定");
                                functionContainer.revalidate();
                                functionContainer.repaint();
                            });
                            // 场地管理的点击事件
                            venueManagementItem.addActionListener(e1 -> {
                                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                functionContainer.removeAll();
                                JPanel venueManagementPanel = createVenueManagement();
                                functionContainer.add(venueManagementPanel, "场地管理");
                                cardLayout.show(functionContainer, "场地管理");
                                functionContainer.revalidate();
                                functionContainer.repaint();
                            });
                        });
                    } else if ("电影票管理".equals(option)) {
                        // 创建电影票管理弹出菜单
                        JPopupMenu popupMenu = new JPopupMenu();

                        // 创建子选项
                        JMenuItem refundItem = new JMenuItem("处理退票申请");
                        JMenuItem venueBookingItem = new JMenuItem("电影场地预定");
                        JMenuItem screeningManagementItem = new JMenuItem("电影场次管理");

                        // 设置子选项样式
                        for (JMenuItem item : new JMenuItem[]{refundItem, venueBookingItem, screeningManagementItem}) {
                            item.setFont(new Font("楷体", Font.BOLD, 18));
                            item.setBackground(new Color(240, 248, 255));
                            item.setBorderPainted(false);
                            item.setFocusPainted(false);
                            item.setContentAreaFilled(false);
                            item.setOpaque(true);
                        }

                        // 处理退票申请子选项点击事件
                        refundItem.addActionListener(e1 -> {
                            handleRefundApplications();
                        });

                        // 电影场地预定子选项点击事件
                        venueBookingItem.addActionListener(e1 -> {
                            movieVenueBooking();
                        });

                        // 电影场次管理子选项点击事件
                        screeningManagementItem.addActionListener(e1 -> {
                            movieScreeningManagement();
                        });

                        // 添加子选项到弹出菜单
                        popupMenu.add(refundItem);
                        popupMenu.add(venueBookingItem);
                        popupMenu.add(screeningManagementItem);

                        optionButton.addActionListener(e2 -> {
                            // 显示弹出菜单
                            popupMenu.show(optionButton, optionButton.getWidth(), 0);
                        });
                    } else {
                        optionButton.addActionListener(e2 -> {
                            if ("退出登录".equals(option)) {
                                // 获取当前窗口
                                Window currentWindow = SwingUtilities.getWindowAncestor((Component) e2.getSource());
                                // 关闭当前窗口
                                currentWindow.dispose();
                                // 重置登录状态
                                loggedInUserID = -1;
                                // 重新创建登录界面
                                EventQueue.invokeLater(() -> {
                                    try {
                                        createLoginFrame();
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                });
                            } else {
                                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                functionContainer.removeAll();
                                JPanel adminPanel = createAdminFunctionPanel(option);
                                functionContainer.add(adminPanel, option);
                                cardLayout.show(functionContainer, option);
                                functionContainer.revalidate();
                                functionContainer.repaint();
                            }
                        });
                    }
                    sidebarPanel.add(optionButton);
                }

                // 添加欢迎面板
                JPanel welcomePanel = new JPanel();
                welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.Y_AXIS));
                welcomePanel.setBackground(new Color(240, 248, 255));
                JLabel welcomeLabel = new JLabel("欢迎使用电影票务管理系统");
                welcomeLabel.setFont(new Font("隶书", Font.PLAIN, 30));
                welcomeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
                welcomePanel.add(welcomeLabel);
                functionContainer.add(welcomePanel, "welcome");
                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                cardLayout.show(functionContainer, "welcome");

                adminFrame.add(sidebarPanel, BorderLayout.WEST);
                adminFrame.setVisible(true);
                frame.dispose();
            } else {
                // 再尝试以普通用户身份登录
                loggedInUserID = UserService.login(username, password, false);
                if (loggedInUserID != -1) {
                    JOptionPane.showMessageDialog(frame, "普通用户登录成功！");
                    // 清空窗口信息
                    frame.getContentPane().removeAll();

                    // 创建侧边栏面板，使用 BoxLayout
                    JPanel sidebarPanel = new JPanel();
                    sidebarPanel.setLayout(new BoxLayout(sidebarPanel, BoxLayout.Y_AXIS));
                    sidebarPanel.setBackground(new Color(0, 150, 200)); // 设置侧边栏背景色
                    // 添加“退出登录”选项
                    String[] options = {"票务销售", "票务查询", "个人中心", "退出登录"};
                    TicketingService ticketingService = new TicketingService();

                    // 使用 CardLayout 管理功能界面
                    JPanel functionContainer = new JPanel(new CardLayout());
                    functionContainer.setBackground(new Color(240, 248, 255)); // 设置功能界面背景色
                    frame.add(functionContainer, BorderLayout.CENTER);

                    for (String option : options) {
                        JButton optionButton = new JButton(option);
                        optionButton.setFont(new Font("楷体", Font.BOLD, 20));
                        optionButton.setBackground(new Color(0, 150, 200));
                        optionButton.setBorderPainted(false);
                        optionButton.setFocusPainted(false);
                        optionButton.setContentAreaFilled(false);
                        optionButton.setOpaque(true);

                        if ("个人中心".equals(option)) {
                            // 创建弹出菜单
                            JPopupMenu popupMenu = new JPopupMenu();

                            // 创建子选项
                            JMenuItem personalInfoItem = new JMenuItem("个人信息");
                            JMenuItem myOrdersItem = new JMenuItem("我的订单");

                            // 设置子选项样式与主按钮一致
                            personalInfoItem.setFont(new Font("楷体", Font.BOLD, 20));
                            personalInfoItem.setBackground(new Color(240, 248, 255));
                            personalInfoItem.setBorderPainted(false);
                            personalInfoItem.setFocusPainted(false);
                            personalInfoItem.setContentAreaFilled(false);
                            personalInfoItem.setOpaque(true);

                            myOrdersItem.setFont(new Font("楷体", Font.BOLD, 20));
                            myOrdersItem.setBackground(new Color(240, 248, 255));
                            myOrdersItem.setBorderPainted(false);
                            myOrdersItem.setFocusPainted(false);
                            myOrdersItem.setContentAreaFilled(false);
                            myOrdersItem.setOpaque(true);

                            // 添加子选项到弹出菜单
                            popupMenu.add(personalInfoItem);
                            popupMenu.add(myOrdersItem);

                            optionButton.addActionListener(e1 -> {
                                // 显示弹出菜单
                                popupMenu.show(optionButton, optionButton.getWidth(), 0);
                            });

                            // 子选项的点击事件
                            personalInfoItem.addActionListener(e2 -> {
                                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                functionContainer.removeAll();
                                JPanel personalInfoPanel = createPersonalInfoPanel();
                                functionContainer.add(personalInfoPanel, "个人信息");
                                cardLayout.show(functionContainer, "个人信息");
                                functionContainer.revalidate();
                                functionContainer.repaint();
                            });

                            myOrdersItem.addActionListener(e2 -> {
                                CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                functionContainer.removeAll();
                                JPanel myOrdersPanel = createMyOrdersPanel(ticketingService);
                                functionContainer.add(myOrdersPanel, "我的订单");
                                cardLayout.show(functionContainer, "我的订单");
                                functionContainer.revalidate();
                                functionContainer.repaint();
                            });
                        } else {
                            optionButton.addActionListener(e1 -> {
                                if ("退出登录".equals(option)) {
                                    // 获取当前窗口
                                    Window currentWindow = SwingUtilities.getWindowAncestor((Component) e1.getSource());
                                    // 关闭当前窗口
                                    currentWindow.dispose();
                                    // 重置登录状态
                                    loggedInUserID = -1;
                                    // 重新创建登录界面
                                    EventQueue.invokeLater(() -> {
                                        try {
                                            createLoginFrame();
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    });
                                } else {
                                    CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                                    functionContainer.removeAll(); // 清空旧界面
                                    JPanel newFunctionPanel = createFunctionPanel(option, ticketingService, functionContainer);
                                    functionContainer.add(newFunctionPanel, option);
                                    cardLayout.show(functionContainer, option); // 切换到新界面
                                    functionContainer.revalidate();
                                    functionContainer.repaint();
                                }
                            });
                        }
                        sidebarPanel.add(optionButton);
                    }

                    // 添加欢迎面板
                    JPanel welcomePanel = new JPanel();
                    welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.Y_AXIS));
                    welcomePanel.setBackground(new Color(240, 248, 255));
                    JLabel welcomeLabel = new JLabel("欢迎使用电影票务管理系统");
                    welcomeLabel.setFont(new Font("隶书", Font.PLAIN, 30));
                    welcomeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
                    welcomePanel.add(welcomeLabel);
                    functionContainer.add(welcomePanel, "welcome");
                    CardLayout cardLayout = (CardLayout) functionContainer.getLayout();
                    cardLayout.show(functionContainer, "welcome");

                    // 将侧边栏面板添加到窗口的西侧
                    frame.add(sidebarPanel, BorderLayout.WEST);

                    frame.revalidate();
                    frame.repaint();
                } else {
                    JOptionPane.showMessageDialog(frame, "登录失败，请检查用户名和密码。");
                }
            }
        });

        // 添加组件
        JPanel centerPanel = new JPanel(new GridLayout(0, 1, 5, 5));
        centerPanel.add(titlePanel);
        centerPanel.add(userPanel);
        centerPanel.add(passPanel);
        centerPanel.add(btnPanel);
        centerPanel.add(changepwdPanel);

        frame.add(centerPanel, BorderLayout.CENTER);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Conn.closeDataSource();
            }
        });
    }

    // 普通用户登录成功界面
    private static JPanel createFunctionPanel(String option, TicketingService ticketingService, JPanel functionContainer) {
        JPanel functionPanel = new JPanel();
        functionPanel.setLayout(new BoxLayout(functionPanel, BoxLayout.Y_AXIS)); // 使用垂直 BoxLayout
        functionPanel.setBackground(new Color(240, 248, 255)); // 设置功能面板背景色

        switch (option) {
            case "票务销售":
                return createTicketSalesPanel();

            case "票务查询":
                JLabel ticketQueryLabel = new JLabel("电影查询");
                ticketQueryLabel.setFont(new Font("隶书", Font.PLAIN, 24));
                ticketQueryLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
                functionPanel.add(ticketQueryLabel);

                // 结果显示区域，使用表格
                JPanel resultPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
                resultPanel.setBackground(new Color(240, 248, 255));
                String[] columnNames2 = {"电影名", "上映年份", "主演", "导演", "编剧"};
                DefaultTableModel tableModel2 = new DefaultTableModel(columnNames2, 0);
                JTable ticketTable = new JTable(tableModel2);
                JScrollPane scrollPane1 = new JScrollPane(ticketTable);
                scrollPane1.setPreferredSize(new Dimension(600, 200));
                resultPanel.add(scrollPane1);
                functionPanel.add(resultPanel);

                // 电影名称输入
                JPanel queryMovieNamePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
                queryMovieNamePanel.setBackground(new Color(240, 248, 255));
                JLabel queryMovieNameLabel = new JLabel("电影名称 (留空查询所有):");
                queryMovieNameLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                JTextField queryMovieNameField = new JTextField(20);
                queryMovieNamePanel.add(queryMovieNameLabel);
                queryMovieNamePanel.add(queryMovieNameField);
                functionPanel.add(queryMovieNamePanel);

                // 查询按钮
                JPanel queryButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
                queryButtonPanel.setBackground(new Color(240, 248, 255));
                JButton queryButton = new JButton("查询");
                queryButtonPanel.add(queryButton);
                functionPanel.add(queryButtonPanel);

                // 定义查询方法，避免代码重复
                java.util.function.Consumer<String> performQuery = movieName -> {
                    List<Movie> movies = TicketingService.queryMovies(movieName.isEmpty() ? null : movieName);
                    tableModel2.setRowCount(0); // 清空表格数据
                    for (Movie movie : movies) {
                        Object[] rowData = {
                                movie.getMovieName(),
                                movie.getReleaseYear(),
                                movie.getActors(),
                                movie.getDirector(),
                                movie.getScreenwriter()
                        };
                        tableModel2.addRow(rowData);
                    }
                };

                // 初始查询，显示所有电影信息
                performQuery.accept("");

                // 查询按钮事件
                queryButton.addActionListener(e -> {
                    String movieName = queryMovieNameField.getText().trim();
                    performQuery.accept(movieName);
                });

                // 添加表格点击事件
                ticketTable.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        int selectedRow = ticketTable.getSelectedRow();
                        if (selectedRow != -1) {
                            try {
                                String movieName = (String) ticketTable.getValueAt(selectedRow, 0);
                                int releaseYear = (int) ticketTable.getValueAt(selectedRow, 1);
                                String actors = (String) ticketTable.getValueAt(selectedRow, 2);
                                String director = (String) ticketTable.getValueAt(selectedRow, 3);
                                String screenwriter = (String) ticketTable.getValueAt(selectedRow, 4);

                                // 查询剧情简介
                                List<Movie> movies = TicketingService.queryMovies(movieName);
                                String plot = "";
                                for (Movie movie : movies) {
                                    if (movie.getMovieName().equals(movieName)) {
                                        plot = movie.getPlot();
                                        break;
                                    }
                                }

                                // 创建一个 final 变量来存储 plot 的值
                                final String finalPlot = plot;

                                // 在 EDT 中创建并显示弹窗
                                SwingUtilities.invokeLater(() -> {
                                    JFrame detailsFrame = new JFrame("电影详情");
                                    detailsFrame.setSize(400, 300);
                                    detailsFrame.setLayout(new GridLayout(0, 1, 5, 5));
                                    detailsFrame.setLocationRelativeTo(null);

                                    detailsFrame.add(new JLabel("电影名: " + movieName));
                                    detailsFrame.add(new JLabel("上映年份: " + releaseYear));
                                    detailsFrame.add(new JLabel("主演: " + actors));
                                    detailsFrame.add(new JLabel("导演: " + director));
                                    detailsFrame.add(new JLabel("编剧: " + screenwriter));

                                    // 使用 JTextArea 显示剧情简介
                                    JTextArea plotTextArea = new JTextArea(finalPlot);
                                    plotTextArea.setEditable(false);
                                    plotTextArea.setLineWrap(true);
                                    plotTextArea.setWrapStyleWord(true);
                                    JScrollPane plotScrollPane = new JScrollPane(plotTextArea);
                                    detailsFrame.add(plotScrollPane);

                                    detailsFrame.setVisible(true);
                                });
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                });
                break;
        }
        return functionPanel;
    }

    // 票务销售功能
    private static JPanel createTicketSalesPanel() {
        JPanel ticketSalesPanel = new JPanel(new BorderLayout());
        ticketSalesPanel.setBackground(new Color(240, 248, 255));

        // 标题
        JLabel ticketSalesLabel = new JLabel("票务销售");
        ticketSalesLabel.setFont(new Font("隶书", Font.PLAIN, 24));
        ticketSalesLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        ticketSalesPanel.add(ticketSalesLabel, BorderLayout.NORTH);

        // 电影信息显示，使用 JTable
        JPanel movieInfoPanel = new JPanel(new BorderLayout());
        movieInfoPanel.setBackground(new Color(240, 248, 255));
        String[] movieColumnNames = {"电影ID", "电影名称", "上映年份", "主演", "导演", "编剧"};
        DefaultTableModel movieTableModel = new DefaultTableModel(movieColumnNames, 0);
        JTable movieTable = new JTable(movieTableModel);
        JScrollPane movieScrollPane = new JScrollPane(movieTable);

        // 将滚动面板添加到电影信息面板的中心位置，使其填充可用空间
        movieInfoPanel.add(movieScrollPane, BorderLayout.CENTER);
        ticketSalesPanel.add(movieInfoPanel, BorderLayout.CENTER);

        // 从数据库获取电影信息
        try (Connection conn = Conn.getConn()) {
            String sql = "SELECT MovieID, MovieName, ReleaseYear, Actors, Director, Screenwriter FROM Movies";
            try (PreparedStatement pstmt = conn.prepareStatement(sql);
                 ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = {
                            rs.getInt("MovieID"),
                            rs.getString("MovieName"),
                            rs.getInt("ReleaseYear"),
                            rs.getString("Actors"),
                            rs.getString("Director"),
                            rs.getString("Screenwriter")
                    };
                    movieTableModel.addRow(rowData);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 添加电影表格点击事件
        movieTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = movieTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 弹出窗口显示影院及影厅信息
                    JFrame venueHallFrame = new JFrame("影院及影厅信息");
                    venueHallFrame.setSize(600, 400);
                    venueHallFrame.setLayout(new BorderLayout());
                    venueHallFrame.setLocationRelativeTo(null);  // 将此窗口也居中显示

                    // 从数据库获取该电影对应的影院及影厅信息
                    String movieName = (String) movieTableModel.getValueAt(selectedRow, 1);
                    String[] venueHallColumnNames = {"影院名", "影厅名", "开始日期", "结束日期", "开始时间", "结束时间", "票价"};
                    DefaultTableModel venueHallTableModel = new DefaultTableModel(venueHallColumnNames, 0);
                    JTable venueHallTable = new JTable(venueHallTableModel);
                    JScrollPane venueHallScrollPane = new JScrollPane(venueHallTable);

                    try (Connection conn = Conn.getConn()) {
                        // 添加 TicketPrice > 0 的过滤条件
                        String sql = "SELECT VenueName, HallName, StartDate, EndDate, StartTime, EndTime, TicketPrice " +
                                "FROM MovieVenueBookings WHERE MovieName = ? AND TicketPrice > 0";
                        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                            pstmt.setString(1, movieName);
                            try (ResultSet rs = pstmt.executeQuery()) {
                                while (rs.next()) {
                                    Object[] rowData = {
                                            rs.getString("VenueName"),
                                            rs.getString("HallName"),
                                            rs.getDate("StartDate"),
                                            rs.getDate("EndDate"),
                                            rs.getTime("StartTime"),
                                            rs.getTime("EndTime"),
                                            rs.getBigDecimal("TicketPrice") // 获取票价信息
                                    };
                                    venueHallTableModel.addRow(rowData);
                                }
                            }
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }

                    venueHallFrame.add(venueHallScrollPane, BorderLayout.CENTER);

                    // 添加影院及影厅表格点击事件
                    venueHallTable.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            int selectedVenueRow = venueHallTable.getSelectedRow();
                            if (selectedVenueRow != -1) {
                                // 获取选中的影院和影厅信息
                                String venueName = (String) venueHallTableModel.getValueAt(selectedVenueRow, 0);
                                String hallName = (String) venueHallTableModel.getValueAt(selectedVenueRow, 1);

                                // 弹出窗口显示座位信息
                                JFrame seatFrame = new JFrame("座位信息 - " + venueName + " - " + hallName);
                                seatFrame.setSize(800, 600);
                                seatFrame.setLocationRelativeTo(null);  // 将座位表界面居中显示

                                // 获取影厅容量
                                int hallCapacity = 0;
                                try (Connection conn = Conn.getConn()) {
                                    String sql = "SELECT HallCapacity FROM Halls " +
                                            "JOIN Venues ON Halls.VenueID = Venues.VenueID " +
                                            "WHERE Venues.VenueName = ? AND Halls.HallName = ?";
                                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                                        pstmt.setString(1, venueName);
                                        pstmt.setString(2, hallName);
                                        try (ResultSet rs = pstmt.executeQuery()) {
                                            if (rs.next()) {
                                                hallCapacity = rs.getInt("HallCapacity");
                                            }
                                        }
                                    }
                                } catch (SQLException ex) {
                                    ex.printStackTrace();
                                }

                                // 计算座位的行数和列数，假设每行最多 10 个座位
                                int rows = (int) Math.ceil((double) hallCapacity / 10);
                                int cols = 10; // 每行最多 10 个座位

                                // 创建座位面板
                                JPanel seatPanel = new JPanel(new GridLayout(rows, cols, 5, 5));
                                seatPanel.setBackground(new Color(240, 248, 255));

                                // 从数据库获取该影厅的座位信息
                                try (Connection conn = Conn.getConn()) {
                                    String sql = "SELECT SeatID, SeatNumber, SeatStatus, SeatRow, SeatColumn FROM Seats " +
                                            "JOIN Halls ON Seats.HallID = Halls.HallID " +
                                            "JOIN Venues ON Halls.VenueID = Venues.VenueID " +
                                            "WHERE Venues.VenueName = ? AND Halls.HallName = ?";
                                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                                        pstmt.setString(1, venueName);
                                        pstmt.setString(2, hallName);
                                        try (ResultSet rs = pstmt.executeQuery()) {
                                            // 创建一个座位状态数组，用于标记座位是否已售
                                            boolean[] seatStatusArray = new boolean[hallCapacity];
                                            while (rs.next()) {
                                                String seatNumber = rs.getString("SeatNumber");
                                                String seatStatus = rs.getString("SeatStatus");
                                                int seatIndex = Integer.parseInt(seatNumber) - 1;
                                                seatStatusArray[seatIndex] = "已售出".equals(seatStatus);
                                            }

                                            // 生成座位按钮
                                            for (int i = 0; i < hallCapacity; i++) {
                                                String seatNumber = String.valueOf(i + 1);
                                                JButton seatButton = new JButton(seatNumber);
                                                seatButton.setFont(new Font("楷书", Font.PLAIN, 12));
                                                seatButton.setPreferredSize(new Dimension(30, 30)); // 缩小按钮大小
                                                if (seatStatusArray[i]) {
                                                    seatButton.setBackground(new Color(200, 100, 100));
                                                    seatButton.setEnabled(false); // 已售座位不可点击
                                                } else {
                                                    seatButton.setBackground(new Color(0, 150, 100));
                                                    seatButton.addActionListener(seatEvent -> {
                                                        if (seatStatusArray[Integer.parseInt(seatButton.getText()) - 1]) {
                                                            JOptionPane.showMessageDialog(seatFrame, "该座位已被购买！");
                                                        } else {
                                                            // 标记座位为选中状态（可以通过改变按钮颜色等方式）
                                                            seatButton.setBackground(Color.YELLOW);
                                                        }
                                                    });
                                                }
                                                seatPanel.add(seatButton);
                                            }
                                        }
                                    }
                                } catch (SQLException ex) {
                                    ex.printStackTrace();
                                }

                                // 添加支付方式选项和购买按钮
                                JPanel paymentPanel = new JPanel();
                                ButtonGroup paymentGroup = new ButtonGroup();
                                JRadioButton wechatPayment = new JRadioButton("微信支付");
                                JRadioButton alipayPayment = new JRadioButton("支付宝支付");
                                paymentGroup.add(wechatPayment);
                                paymentGroup.add(alipayPayment);
                                paymentPanel.add(wechatPayment);
                                paymentPanel.add(alipayPayment);

                                JButton buyButton = new JButton("购买");
                                buyButton.addActionListener(buyEvent -> {
                                    String paymentMethod = "";
                                    if (wechatPayment.isSelected()) {
                                        paymentMethod = "微信支付";
                                    } else if (alipayPayment.isSelected()) {
                                        paymentMethod = "支付宝支付";
                                    }

                                    // 获取选中的座位号
                                    StringBuilder selectedSeats = new StringBuilder();
                                    Component[] components = seatPanel.getComponents();
                                    for (Component component : components) {
                                        if (component instanceof JButton) {
                                            JButton seatButton = (JButton) component;
                                            if (seatButton.getBackground().equals(Color.YELLOW)) {
                                                if (!selectedSeats.isEmpty()) {
                                                    selectedSeats.append(",");
                                                }
                                                selectedSeats.append(seatButton.getText());
                                            }
                                        }
                                    }

                                    if (paymentMethod.isEmpty()) {
                                        JOptionPane.showMessageDialog(seatFrame, "请选择支付方式！");
                                        return;
                                    }
                                    if (selectedSeats.isEmpty()) {
                                        JOptionPane.showMessageDialog(seatFrame, "请选择座位！");
                                        return;
                                    }

                                    // 获取电影名、电影院名、影厅名和单价
                                    String movieName = (String) movieTableModel.getValueAt(selectedRow, 1);
                                    String venueName1 = (String) venueHallTableModel.getValueAt(selectedVenueRow, 0);
                                    String hallName1 = (String) venueHallTableModel.getValueAt(selectedVenueRow, 1);
                                    int quantity = selectedSeats.toString().split(",").length; // 获取选座个数
                                    BigDecimal ticketPrice = (BigDecimal) venueHallTableModel.getValueAt(selectedVenueRow, 6); // 获取票价
                                    BigDecimal totalPrice = ticketPrice.multiply(new BigDecimal(quantity)); // 计算总价

                                    // 获取电影的开始时间、日期和结束时间
                                    java.sql.Date startDate = (java.sql.Date) venueHallTableModel.getValueAt(selectedVenueRow, 2);
                                    java.sql.Time startTime = (java.sql.Time) venueHallTableModel.getValueAt(selectedVenueRow, 4);
                                    java.sql.Date endDate = (java.sql.Date) venueHallTableModel.getValueAt(selectedVenueRow, 3);
                                    java.sql.Time endTime = (java.sql.Time) venueHallTableModel.getValueAt(selectedVenueRow, 5);

                                    // 添加确认支付对话框，并显示购票数量及总价
                                    int confirm = JOptionPane.showConfirmDialog(seatFrame,
                                            "确认使用 " + paymentMethod + " 支付购买座位：" + selectedSeats + " 吗？\n购票数量：" + quantity + "\n总价：" + totalPrice,
                                            "确认支付", JOptionPane.YES_NO_OPTION);
                                    if (confirm == JOptionPane.NO_OPTION) {
                                        // 取消支付时，将选中的座位状态改回未选中
                                        for (Component component : components) {
                                            if (component instanceof JButton) {
                                                JButton seatButton = (JButton) component;
                                                if (seatButton.getBackground().equals(Color.YELLOW)) {
                                                    seatButton.setBackground(new Color(0, 150, 100));
                                                }
                                            }
                                        }
                                        return;
                                    }

                                    try {
                                        // 获取电影名、电影院名、影厅名和单价
                                        int userID = loggedInUserID;

                                        try (Connection conn = Conn.getConn()) {
                                            // 查询 MovieID
                                            String selectMovieIdSql = "SELECT MovieID FROM Movies WHERE MovieName = ?";
                                            try (PreparedStatement selectMovieIdStmt = conn.prepareStatement(selectMovieIdSql)) {
                                                selectMovieIdStmt.setString(1, movieName);
                                                ResultSet movieIdResultSet = selectMovieIdStmt.executeQuery();
                                                int movieId = -1;
                                                if (movieIdResultSet.next()) {
                                                    movieId = movieIdResultSet.getInt("MovieID");
                                                }

                                                // 查询 VenueID
                                                String selectVenueIdSql = "SELECT VenueID FROM Venues WHERE VenueName = ?";
                                                try (PreparedStatement selectVenueIdStmt = conn.prepareStatement(selectVenueIdSql)) {
                                                    selectVenueIdStmt.setString(1, venueName1);
                                                    ResultSet venueIdResultSet = selectVenueIdStmt.executeQuery();
                                                    int venueId = -1;
                                                    if (venueIdResultSet.next()) {
                                                        venueId = venueIdResultSet.getInt("VenueID");
                                                    }

                                                    // 查询 HallID
                                                    String selectHallIdSql = "SELECT HallID FROM Halls WHERE HallName = ? AND VenueID = ?";
                                                    try (PreparedStatement selectHallIdStmt = conn.prepareStatement(selectHallIdSql)) {
                                                        selectHallIdStmt.setString(1, hallName1);
                                                        selectHallIdStmt.setInt(2, venueId);
                                                        ResultSet hallIdResultSet = selectHallIdStmt.executeQuery();
                                                        int hallId = -1;
                                                        if (hallIdResultSet.next()) {
                                                            hallId = hallIdResultSet.getInt("HallID");
                                                        }

                                                        // 插入订单记录到数据库，包括时间信息
                                                        String insertOrderSql = "INSERT INTO Orders (UserID, OrderDate, TotalAmount, MovieID, VenueID, HallID, OrderStatus, Quantity, TicketPrice, StartTime, EndTime, StartDate) " +
                                                                "VALUES (?, NOW(), ?, ?, ?, ?, '未完成', ?, ?, ?, ?, ?)";
                                                        try (PreparedStatement insertOrderStmt = conn.prepareStatement(insertOrderSql)) {
                                                            insertOrderStmt.setInt(1, userID);
                                                            insertOrderStmt.setInt(2, totalPrice.intValue()); // 使用计算出的总价
                                                            insertOrderStmt.setInt(3, movieId);
                                                            insertOrderStmt.setInt(4, venueId);
                                                            insertOrderStmt.setInt(5, hallId);
                                                            insertOrderStmt.setInt(6, quantity); // 插入选座个数
                                                            insertOrderStmt.setBigDecimal(7, ticketPrice); // 插入票价
                                                            insertOrderStmt.setTime(8, startTime); // 插入开始时间
                                                            insertOrderStmt.setTime(9, endTime); // 插入结束时间
                                                            insertOrderStmt.setDate(10, startDate); // 插入开始日期
                                                            insertOrderStmt.executeUpdate();

                                                            // 更新座位状态为已售出
                                                            for (String seatNumber : selectedSeats.toString().split(",")) {
                                                                String updateSql = "UPDATE Seats SET SeatStatus = '已售出' WHERE SeatNumber = ? AND " +
                                                                        "HallID = (SELECT HallID FROM Halls JOIN Venues ON Halls.VenueID = Venues.VenueID " +
                                                                        "WHERE Venues.VenueName = ? AND Halls.HallName = ?)";
                                                                try (PreparedStatement updatePstmt = conn.prepareStatement(updateSql)) {
                                                                    updatePstmt.setString(1, seatNumber);
                                                                    updatePstmt.setString(2, venueName1);
                                                                    updatePstmt.setString(3, hallName1);
                                                                    updatePstmt.executeUpdate();
                                                                    // 找到对应的座位按钮并更新其状态
                                                                    for (Component component : components) {
                                                                        if (component instanceof JButton) {
                                                                            JButton seatButton = (JButton) component;
                                                                            if (seatButton.getText().equals(seatNumber)) {
                                                                                seatButton.setBackground(new Color(200, 100, 100));
                                                                                seatButton.setEnabled(false);
                                                                                break;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (SQLException ex) {
                                            ex.printStackTrace();
                                        }

                                        JOptionPane.showMessageDialog(seatFrame, "购票成功！");
                                        seatFrame.dispose();
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        JOptionPane.showMessageDialog(seatFrame, "购票失败，请稍后重试。");
                                    }
                                });

                                JPanel bottomPanel = new JPanel();
                                bottomPanel.add(paymentPanel);
                                bottomPanel.add(buyButton);
                                seatFrame.add(bottomPanel, BorderLayout.SOUTH);

                                seatFrame.add(seatPanel, BorderLayout.CENTER);
                                seatFrame.setVisible(true);
                            }
                        }
                    });

                    venueHallFrame.setVisible(true);
                }
            }
        });

        return ticketSalesPanel;
    }

    // 个人中心的个人信息面板
    private static JPanel createPersonalInfoPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBackground(new Color(240, 248, 255));

        JLabel personalCenterLabel = new JLabel("个人信息");
        personalCenterLabel.setFont(new Font("隶书", Font.PLAIN, 24));
        personalCenterLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(personalCenterLabel);

        // 个人信息展示
        JPanel personalInfoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        personalInfoPanel.setBackground(new Color(240, 248, 255));
        JLabel infoLabel = new JLabel("个人信息：");
        infoLabel.setFont(new Font("楷书", Font.PLAIN, 16));
        JTextArea infoArea = new JTextArea(5, 50);
        infoArea.setEditable(false);
        JScrollPane infoScrollPane = new JScrollPane(infoArea);
        personalInfoPanel.add(infoLabel);
        personalInfoPanel.add(infoScrollPane);
        panel.add(personalInfoPanel);

        // 显示个人信息
        User user = UserService.getUserInfo(loggedInUserID);
        if (user != null) {
            String info = "用户ID: " + user.getUserID() +
                    "\n用户名: " + user.getUsername() +
                    "\n密码: " + "******" + // 密码以星号显示
                    "\n联系信息: " + user.getContactInfo() +
                    "\n用户状态: " + user.getUserType();
            infoArea.setText(info);
        }

        // 修改个人信息按钮
        JPanel modifyInfoPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        modifyInfoPanel.setBackground(new Color(240, 248, 255));
        JButton modifyInfoButton = new JButton("修改个人信息");
        modifyInfoPanel.add(modifyInfoButton);
        panel.add(modifyInfoPanel);

        // 修改个人信息事件
        modifyInfoButton.addActionListener(e -> {
            JFrame modifyFrame = new JFrame("修改个人信息");
            modifyFrame.setSize(400, 300);
            modifyFrame.setLayout(new GridLayout(6, 2, 10, 10)); // 调整为6行2列布局
            modifyFrame.setLocationRelativeTo(null);

            JLabel userIdLabel = new JLabel("用户ID:");
            userIdLabel.setFont(new Font("楷体", Font.PLAIN, 16));
            JTextField userIdField = new JTextField(String.valueOf(user.getUserID()));
            userIdField.setEditable(false);

            JLabel usernameLabel = new JLabel("用户名:");
            usernameLabel.setFont(new Font("楷体", Font.PLAIN, 16));
            JTextField usernameField = new JTextField(user.getUsername());
            usernameField.setEditable(false);

            JLabel passwordLabel = new JLabel("密码:");
            passwordLabel.setFont(new Font("楷体", Font.PLAIN, 16));
            JPasswordField passwordField = new JPasswordField(user.getPassword());

            JLabel contactInfoLabel = new JLabel("联系信息:");
            contactInfoLabel.setFont(new Font("楷体", Font.PLAIN, 16));
            JTextField contactInfoField = new JTextField(user.getContactInfo());

            JLabel userTypeLabel = new JLabel("用户状态:");
            userTypeLabel.setFont(new Font("楷体", Font.PLAIN, 16));
            JTextField userTypeField = new JTextField(user.getUserType());
            userTypeField.setEditable(false);

            JLabel emptyLabel = new JLabel(); // 添加空白标签用于排版
            JButton saveButton = new JButton("保存");
            saveButton.addActionListener(saveEvent -> {
                String newPassword = new String(passwordField.getPassword());
                String newContactInfo = contactInfoField.getText();
                String userType = userTypeField.getText(); // 获取用户类型
                boolean result = UserService.updateUserInfo(loggedInUserID, newPassword, newContactInfo, userType);
                if (result) {
                    JOptionPane.showMessageDialog(modifyFrame, "个人信息修改成功！");
                    // 更新显示的个人信息
                    String newInfo = "用户ID: " + user.getUserID() +
                            "\n用户名: " + user.getUsername() +
                            "\n密码: " + "******" +
                            "\n联系信息: " + newContactInfo +
                            "\n用户状态: " + userType;
                    infoArea.setText(newInfo);
                    modifyFrame.dispose();
                } else {
                    JOptionPane.showMessageDialog(modifyFrame, "个人信息修改失败，请稍后重试！");
                }
            });

            modifyFrame.add(userIdLabel);
            modifyFrame.add(userIdField);
            modifyFrame.add(usernameLabel);
            modifyFrame.add(usernameField);
            modifyFrame.add(passwordLabel);
            modifyFrame.add(passwordField);
            modifyFrame.add(contactInfoLabel);
            modifyFrame.add(contactInfoField);
            modifyFrame.add(userTypeLabel);
            modifyFrame.add(userTypeField);
            modifyFrame.add(emptyLabel); // 添加空白标签
            modifyFrame.add(saveButton);
            modifyFrame.setVisible(true);
        });

        return panel;
    }

    // 个人中心 我的订单面板
    private static JPanel createMyOrdersPanel(TicketingService ticketingService) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBackground(new Color(240, 248, 255));

        JLabel myOrdersLabel = new JLabel("我的订单");
        myOrdersLabel.setFont(new Font("隶书", Font.PLAIN, 24));
        myOrdersLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(myOrdersLabel);

        // 订单列表
        JPanel orderListPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        orderListPanel.setBackground(new Color(240, 248, 255));
        // 修改列名
        String[] columnNames1 = {"订单ID", "开始日期", "开始时间", "结束时间", "订单状态", "电影名", "影院名", "影厅名"};
        DefaultTableModel tableModel1 = new DefaultTableModel(columnNames1, 0);
        JTable orderTable = new JTable(tableModel1);
        JScrollPane orderScrollPane = new JScrollPane(orderTable);
        orderScrollPane.setPreferredSize(new Dimension(600, 200));
        orderListPanel.add(orderScrollPane);
        panel.add(orderListPanel);

        // 查看订单按钮
        JPanel viewOrdersPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        viewOrdersPanel.setBackground(new Color(240, 248, 255));
        JButton viewOrdersButton = new JButton("查看我的订单");
        viewOrdersPanel.add(viewOrdersButton);
        panel.add(viewOrdersPanel);

        // 查看订单事件
        viewOrdersButton.addActionListener(e -> {
            List<Order> orders = ticketingService.getOrdersByUser(loggedInUserID);
            tableModel1.setRowCount(0); // 清空旧数据
            for (Order order : orders) {
                Object[] rowData = {
                        order.getOrderID(),
                        order.getStartDate(), // 修改为获取 StartDate
                        order.getStartTime(), // 添加获取 StartTime
                        order.getEndTime(), // 添加获取 EndTime
                        order.getOrderStatus(),
                        order.getMovieName(),
                        order.getVenueName(),
                        order.getHallName()
                };
                tableModel1.addRow(rowData);
            }
        });

        // 订单详情点击事件
        orderTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = orderTable.getSelectedRow();
                if (selectedRow != -1) {
                    int orderID = (int) orderTable.getValueAt(selectedRow, 0);
                    Order order = ticketingService.getOrderDetails(orderID);
                    if (order != null) {
                        JFrame detailsFrame = new JFrame("订单详情 - 订单ID: " + orderID);
                        detailsFrame.setSize(400, 300);
                        detailsFrame.setLocationRelativeTo(null);
                        detailsFrame.setLayout(new GridLayout(0, 1, 5, 5));
                        detailsFrame.getContentPane().setBackground(new Color(240, 248, 255));

                        JLabel orderIdLabel = new JLabel("订单ID: " + order.getOrderID());
                        detailsFrame.add(orderIdLabel);
                        // 修改为显示 StartDate、StartTime 和 EndTime
                        JLabel startDateLabel = new JLabel("开始日期: " + order.getStartDate());
                        detailsFrame.add(startDateLabel);
                        JLabel startTimeLabel = new JLabel("开始时间: " + order.getStartTime());
                        detailsFrame.add(startTimeLabel);
                        JLabel endTimeLabel = new JLabel("结束时间: " + order.getEndTime());
                        detailsFrame.add(endTimeLabel);
                        JLabel totalAmountLabel = new JLabel("总金额: " + order.getTotalAmount());
                        detailsFrame.add(totalAmountLabel);
                        JLabel orderStatusLabel = new JLabel("订单状态: " + order.getOrderStatus());
                        detailsFrame.add(orderStatusLabel);
                        JLabel movieNameLabel = new JLabel("电影名: " + order.getMovieName());
                        detailsFrame.add(movieNameLabel);
                        JLabel venueNameLabel = new JLabel("影院名: " + order.getVenueName());
                        detailsFrame.add(venueNameLabel);
                        JLabel hallNameLabel = new JLabel("影厅名: " + order.getHallName());

                        if ("未完成".equals(order.getOrderStatus())) {
                            JButton refundButton = new JButton("申请退款");
                            detailsFrame.add(refundButton);
                            refundButton.addActionListener(refundEvent -> {
                                applyRefund(orderID); // 调用退款申请方法
                                detailsFrame.dispose(); // 关闭详情窗口
                            });
                        }

                        detailsFrame.setVisible(true);
                    }
                }
            }
        });

        return panel;
    }

    //个人中心 我的订单面板 退款申请
    private static void applyRefund(int orderID) {
        JFrame refundFrame = new JFrame("退款申请");
        refundFrame.setSize(400, 200);
        refundFrame.setLayout(new BorderLayout());
        refundFrame.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new FlowLayout());
        JLabel label = new JLabel("请选择退款理由：");
        JComboBox<String> reasonComboBox = new JComboBox<>();
        try (Connection conn = Conn.getConn()) {
            String sql = "SELECT Description FROM RefundReasons";
            try (PreparedStatement pstmt = conn.prepareStatement(sql);
                 ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    reasonComboBox.addItem(rs.getString("Description"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        JButton applyButton = new JButton("提交申请");
        applyButton.addActionListener(e -> {
            int selectedReasonIndex = reasonComboBox.getSelectedIndex();
            int reasonID = selectedReasonIndex + 1; // 假设理由 ID 从 1 开始
            boolean success = TicketingService.applyForRefund(orderID, reasonID); // 通过实例调用
            if (success) {
                JOptionPane.showMessageDialog(refundFrame, "退款申请已提交，等待审核！");
                refundFrame.dispose();
            } else {
                JOptionPane.showMessageDialog(refundFrame, "退款申请失败，请稍后重试！");
            }
        });

        panel.add(label);
        panel.add(reasonComboBox);
        panel.add(applyButton);
        refundFrame.add(panel, BorderLayout.CENTER);
        refundFrame.setVisible(true);
    }

    // 添加管理员功能面板创建方法
    private static JPanel createAdminFunctionPanel(String option) {
        JPanel functionPanel = new JPanel();
        functionPanel.setLayout(new BoxLayout(functionPanel, BoxLayout.Y_AXIS));
        functionPanel.setBackground(new Color(240, 248, 255));

        switch (option) {
            case "用户管理":
                functionPanel.add(createUserManagement());
                break;
            case "活动门票管理":
                functionPanel.add(createEventTicketManagement());
                break;
        }
        return functionPanel;
    }

    // 管理员功能面板具体实现示例
    private static JPanel createMovieTicketManagement() {
        JPanel panel = new JPanel();
        panel.setBackground(new Color(240, 248, 255));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        JLabel label = new JLabel("电影票管理");
        label.setFont(new Font("隶书", Font.PLAIN, 24));
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(label);
        return panel;
    }

    // 用户管理功能
    private static JPanel createUserManagement() {
        JPanel panel = new JPanel();
        panel.setBackground(new Color(240, 248, 255));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        JLabel label = new JLabel("用户管理");
        label.setFont(new Font("隶书", Font.PLAIN, 24));
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(label);

        // 定义表格列名
        String[] columnNames = {"用户ID", "用户名", "联系信息", "用户状态"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable userTable = new JTable(tableModel);
        JScrollPane userTableScrollPane = new JScrollPane(userTable);
        userTableScrollPane.setPreferredSize(new Dimension(600, 200));
        panel.add(userTableScrollPane);

        // 从数据库获取所有用户信息并填充到表格中
        List<User> users = UserService.getAllUsers();
        for (User user : users) {
            Object[] rowData = {
                    user.getUserID(),
                    user.getUsername(),
                    user.getContactInfo(),
                    user.getUserType()
            };
            tableModel.addRow(rowData);
        }

        // 添加表格点击事件
        userTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = userTable.getSelectedRow();
                if (selectedRow != -1) {
                    int userId = (int) userTable.getValueAt(selectedRow, 0);
                    String username = (String) userTable.getValueAt(selectedRow, 1);
                    String contactInfo = (String) userTable.getValueAt(selectedRow, 2);
                    String userType = (String) userTable.getValueAt(selectedRow, 3);

                    // 弹出修改信息的窗口
                    JFrame modifyFrame = new JFrame("修改用户信息");
                    modifyFrame.setSize(400, 300);
                    modifyFrame.setLayout(new GridLayout(5, 2, 10, 10));
                    modifyFrame.setLocationRelativeTo(null);

                    JLabel userIdLabel = new JLabel("用户ID:");
                    userIdLabel.setFont(new Font("楷体", Font.PLAIN, 16));
                    JTextField userIdField = new JTextField(String.valueOf(userId));
                    userIdField.setEditable(false);
                    JLabel usernameLabel = new JLabel("用户名:");
                    usernameLabel.setFont(new Font("楷体", Font.PLAIN, 16));
                    JTextField usernameField = new JTextField(username);
                    usernameField.setEditable(false);
                    JLabel contactInfoLabel = new JLabel("联系信息:");
                    contactInfoLabel.setFont(new Font("楷体", Font.PLAIN, 16));
                    JTextField contactInfoField = new JTextField(contactInfo);
                    JLabel userTypeLabel = new JLabel("用户状态:");
                    userTypeLabel.setFont(new Font("楷体", Font.PLAIN, 16));
                    JTextField userTypeField = new JTextField(userType);

                    JButton saveButton = new JButton("保存");
                    saveButton.addActionListener(saveEvent -> {
                        String newContactInfo = contactInfoField.getText();
                        String newUserType = userTypeField.getText();
                        boolean result = UserService.updateUserInfo(userId, null, newContactInfo, newUserType);
                        if (result) {
                            JOptionPane.showMessageDialog(modifyFrame, "用户信息修改成功！");
                            // 更新表格数据
                            tableModel.setValueAt(newContactInfo, selectedRow, 2);
                            tableModel.setValueAt(newUserType, selectedRow, 3);
                            modifyFrame.dispose();
                        } else {
                            JOptionPane.showMessageDialog(modifyFrame, "用户信息修改失败，请稍后重试！");
                        }
                    });

                    modifyFrame.add(userIdLabel);
                    modifyFrame.add(userIdField);
                    modifyFrame.add(usernameLabel);
                    modifyFrame.add(usernameField);
                    modifyFrame.add(contactInfoLabel);
                    modifyFrame.add(contactInfoField);
                    modifyFrame.add(userTypeLabel);
                    modifyFrame.add(userTypeField);
                    modifyFrame.add(new JLabel()); // 占位
                    modifyFrame.add(saveButton);
                    modifyFrame.setVisible(true);
                }
            }
        });

        // 用户搜索
        JPanel searchUserPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        searchUserPanel.setBackground(new Color(240, 248, 255));
        JLabel searchKeywordLabel = new JLabel("搜索关键字:");
        searchKeywordLabel.setFont(new Font("楷书", Font.PLAIN, 16));
        JTextField searchKeywordField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchUserPanel.add(searchKeywordLabel);
        searchUserPanel.add(searchKeywordField);
        searchUserPanel.add(searchButton);
        panel.add(searchUserPanel);

        searchButton.addActionListener(e -> {
            String keyword = searchKeywordField.getText();
            List<User> searchResult = UserService.searchUsers(keyword);
            tableModel.setRowCount(0); // 清空表格数据
            for (User user : searchResult) {
                Object[] rowData = {
                        user.getUserID(),
                        user.getUsername(),
                        user.getContactInfo(),
                        user.getUserType()
                };
                tableModel.addRow(rowData);
            }
        });

        return panel;
    }

//    影院场地管理
    // 获取venues表的单个电影信息
    private static Venue getVenueFromDatabase(int venueId) {
        Venue venue = new Venue();
        String sql = "SELECT * FROM Venues WHERE VenueID =?";

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, venueId);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                venue.setVenueID(rs.getInt("VenueID"));
                venue.setVenueName(rs.getString("VenueName"));
                venue.setAddress(rs.getString("Address"));
                venue.setCapacity(rs.getInt("Capacity"));
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return venue;
    }

    // 获得venues表的所有电影信息
    private static List<Venue> getAllVenuesFromDatabase() {
        List<Venue> venues = new ArrayList<>();
        String sql = "SELECT * FROM Venues";

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                Venue venue = new Venue();
                venue.setVenueID(rs.getInt("VenueID"));
                venue.setVenueName(rs.getString("VenueName"));
                venue.setAddress(rs.getString("Address"));
                venue.setCapacity(rs.getInt("Capacity"));
                venues.add(venue);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return venues;
    }

    // 更新venues表的电影信息
    private static boolean updateVenueInDatabase(Venue venue) {
        String sql = "UPDATE Venues SET VenueName=?, Address=?, Capacity=? WHERE VenueID=?";

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, venue.getVenueName());
            pstmt.setString(2, venue.getAddress());
            pstmt.setInt(3, venue.getCapacity());
            pstmt.setInt(4, venue.getVenueID());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    // 插入信息到venues表
    private static boolean addVenueToDatabase(Venue venue) {
        String sql = "INSERT INTO Venues (VenueName, Address, Capacity) VALUES (?, ?, ?)";

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, venue.getVenueName());
            pstmt.setString(2, venue.getAddress());
            pstmt.setInt(3, venue.getCapacity());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    //  删除venues表的信息
    private static boolean deleteVenueFromDatabase(int venueId) {
        String sql = "DELETE FROM Venues WHERE VenueID=?";

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, venueId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    // 场地管理功能
    private static JPanel createVenueManagement() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(240, 248, 255));

        // 添加标题标签
        JLabel venueManagementLabel = new JLabel("场地管理");
        venueManagementLabel.setFont(new Font("隶书", Font.PLAIN, 24));
        venueManagementLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(new Color(240, 248, 255));
        titlePanel.add(venueManagementLabel);
        panel.add(titlePanel, BorderLayout.NORTH);

        // 表格数据
        String[] columnNames = {"场地ID", "影院名", "地址", "容量"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        JTable venueTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(venueTable);

        // 从数据库加载数据
        refreshVenueTable(tableModel);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton modifyBtn = new JButton("修改");
        JButton addBtn = new JButton("新增");
        JButton deleteBtn = new JButton("删除");

        // 设置按钮样式
        for (JButton btn : new JButton[]{modifyBtn, addBtn, deleteBtn}) {
            btn.setFont(new Font("楷体", Font.BOLD, 18));
            btn.setPreferredSize(new Dimension(100, 40));
        }

        // 修改按钮事件
        modifyBtn.addActionListener(e -> {
            int selectedRow = venueTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(panel, "请先选择要修改的场地");
                return;
            }

            int venueId = (int) tableModel.getValueAt(selectedRow, 0);
            Venue venue = getVenueFromDatabase(venueId);

            // 创建修改对话框
            JDialog editDialog = createEditDialog(venue, tableModel);
            editDialog.setVisible(true);
        });

        // 删除按钮事件
        deleteBtn.addActionListener(e -> {
            int selectedRow = venueTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(panel, "请先选择要删除的场地");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(panel, "确定要删除该场地吗？", "确认删除",
                    JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                int venueId = (int) tableModel.getValueAt(selectedRow, 0);
                if (deleteVenueFromDatabase(venueId)) {
                    tableModel.removeRow(selectedRow);
                    JOptionPane.showMessageDialog(panel, "删除成功");
                } else {
                    JOptionPane.showMessageDialog(panel, "删除失败");
                }
            }
        });

        // 新增按钮事件
        addBtn.addActionListener(e -> {
            JDialog addDialog = createAddDialog(tableModel);
            addDialog.setVisible(true);
        });

        buttonPanel.add(modifyBtn);
        buttonPanel.add(addBtn);
        buttonPanel.add(deleteBtn);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 刷新电影表venues格数据
    private static void refreshVenueTable(DefaultTableModel tableModel) {
        tableModel.setRowCount(0);
        List<Venue> venues = getAllVenuesFromDatabase();
        for (Venue venue : venues) {
            Object[] rowData = {
                    venue.getVenueID(),
                    venue.getVenueName(),
                    venue.getAddress(),
                    venue.getCapacity()
            };
            tableModel.addRow(rowData);
        }
    }


    // 创建修改对话框
    private static JDialog createEditDialog(Venue venue, DefaultTableModel tableModel) {
        JDialog dialog = new JDialog();
        dialog.setTitle("修改场地信息");
        dialog.setSize(400, 300);
        dialog.setLayout(new GridLayout(5, 2, 10, 10));

        JLabel nameLabel = new JLabel("影院名:");
        JTextField nameField = new JTextField(venue.getVenueName());
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField(venue.getAddress());
        JLabel capacityLabel = new JLabel("容量:");
        JTextField capacityField = new JTextField(String.valueOf(venue.getCapacity()));

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {
            // 输入验证
            if (nameField.getText().trim().isEmpty() ||
                    addressField.getText().trim().isEmpty() ||
                    !capacityField.getText().matches("\\d+")) {

                JOptionPane.showMessageDialog(dialog, "请输入有效信息");
                return;
            }

            venue.setVenueName(nameField.getText());
            venue.setAddress(addressField.getText());
            venue.setCapacity(Integer.parseInt(capacityField.getText()));

            if (updateVenueInDatabase(venue)) {
                refreshVenueTable(tableModel);
                dialog.dispose();
                JOptionPane.showMessageDialog(dialog, "修改成功");
            } else {
                JOptionPane.showMessageDialog(dialog, "修改失败");
            }
        });

        dialog.add(nameLabel);
        dialog.add(nameField);
        dialog.add(addressLabel);
        dialog.add(addressField);
        dialog.add(capacityLabel);
        dialog.add(capacityField);
        dialog.add(new JLabel());
        dialog.add(saveBtn);
//      居中显示
        dialog.setLocationRelativeTo(null);

        return dialog;
    }

    // 创建新增场地对话框
    private static JDialog createAddDialog(DefaultTableModel tableModel) {
        JDialog dialog = new JDialog();
        dialog.setTitle("新增场地");
        dialog.setSize(400, 300);
        dialog.setLayout(new GridLayout(5, 2, 10, 10));

        JLabel nameLabel = new JLabel("影院名:");
        JTextField nameField = new JTextField();
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField();
        JLabel capacityLabel = new JLabel("容量:");
        JTextField capacityField = new JTextField();

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {
            // 输入验证
            if (nameField.getText().trim().isEmpty() ||
                    addressField.getText().trim().isEmpty() ||
                    !capacityField.getText().matches("\\d+")) {

                JOptionPane.showMessageDialog(dialog, "请输入有效信息");
                return;
            }

            Venue newVenue = new Venue();
            newVenue.setVenueName(nameField.getText());
            newVenue.setAddress(addressField.getText());
            newVenue.setCapacity(Integer.parseInt(capacityField.getText()));

            if (addVenueToDatabase(newVenue)) {
                refreshVenueTable(tableModel);
                dialog.dispose();
                JOptionPane.showMessageDialog(dialog, "新增成功");
            } else {
                JOptionPane.showMessageDialog(dialog, "新增失败");
            }
        });

        dialog.add(nameLabel);
        dialog.add(nameField);
        dialog.add(addressLabel);
        dialog.add(addressField);
        dialog.add(capacityLabel);
        dialog.add(capacityField);
        dialog.add(new JLabel());
        dialog.add(saveBtn);
//      居中显示
        dialog.setLocationRelativeTo(null);

        return dialog;
    }


    //  场地预定
    private static JPanel createVenueBookingPanel(TicketingService ticketingService) {
        JPanel functionPanel = new JPanel();
        functionPanel.setLayout(new BoxLayout(functionPanel, BoxLayout.Y_AXIS));
        functionPanel.setBackground(new Color(240, 248, 255));

        JLabel venueBookingLabel = new JLabel("场地预定");
        venueBookingLabel.setFont(new Font("隶书", Font.PLAIN, 24));
        venueBookingLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        functionPanel.add(venueBookingLabel);

        // 场地信息显示，使用 JTable
        JPanel venueInfoPanel = new JPanel(new BorderLayout()); // 使用 BorderLayout 布局
        venueInfoPanel.setBackground(new Color(240, 248, 255));
        String[] columnNames = {"场地 ID", "影院名", "地址", "容量"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable venueTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(venueTable);

        // 将滚动面板添加到场地信息面板的中心位置，使其填充可用空间
        venueInfoPanel.add(scrollPane, BorderLayout.CENTER);
        functionPanel.add(venueInfoPanel);

        // 从数据库获取场地信息
        List<Venue> venues = ticketingService.getVenues();
        // 使用 Set 来存储已经添加到表格中的场地 VenueID
        Set<Integer> addedVenueIds = new HashSet<>();
        for (Venue venue : venues) {
            int venueId = venue.getVenueID();
            if (!addedVenueIds.contains(venueId)) {
                Object[] rowData = {
                        venueId,
                        venue.getVenueName(),
                        venue.getAddress(),
                        venue.getCapacity()
                };
                tableModel.addRow(rowData);
                addedVenueIds.add(venueId);
            }
        }

        // 添加表格点击事件
        venueTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    int selectedRow = venueTable.getSelectedRow();
                    if (selectedRow != -1) {
                        int venueID = (int) venueTable.getValueAt(selectedRow, 0);

                        // 查找对应的场地信息
                        Venue selectedVenue = null;
                        for (Venue venue : venues) {
                            if (venue.getVenueID() == venueID) {
                                selectedVenue = venue;
                                break;
                            }
                        }

                        if (selectedVenue != null) {
                            JFrame detailsFrame = new JFrame("场地详情");
                            detailsFrame.setSize(400, 300);
                            detailsFrame.setLayout(new BorderLayout());
                            detailsFrame.setLocationRelativeTo(null);

                            JPanel basicInfoPanel = new JPanel(new GridLayout(4, 1));
                            basicInfoPanel.add(new JLabel("场地 ID: " + selectedVenue.getVenueID()));
                            basicInfoPanel.add(new JLabel("影院名: " + selectedVenue.getVenueName()));
                            basicInfoPanel.add(new JLabel("地址: " + selectedVenue.getAddress()));
                            basicInfoPanel.add(new JLabel("容量: " + selectedVenue.getCapacity()));

                            detailsFrame.add(basicInfoPanel, BorderLayout.NORTH);

                            // 查找该场地的所有影厅信息
                            List<Hall> halls = ticketingService.getHallsByVenueId(venueID);
                            String[] hallColumnNames = {"影厅编号", "影厅名", "影厅容量"};
                            DefaultTableModel hallTableModel = new DefaultTableModel(hallColumnNames, 0);
                            JTable hallTable = new JTable(hallTableModel);
                            for (Hall hall : halls) {
                                Object[] rowData = {
                                        hall.getHallID(),
                                        hall.getHallName(),
                                        hall.getHallCapacity()
                                };
                                hallTableModel.addRow(rowData);
                            }
                            JScrollPane hallScrollPane = new JScrollPane(hallTable);
                            detailsFrame.add(hallScrollPane, BorderLayout.CENTER);

                            // 添加影厅表格点击事件
                            hallTable.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    int selectedHallRow = hallTable.getSelectedRow();
                                    if (selectedHallRow != -1) {
                                        int hallID = (int) hallTable.getValueAt(selectedHallRow, 0);

                                        // 弹出输入日期和时间的窗口
                                        JFrame bookingFrame = new JFrame("场地预订");
                                        bookingFrame.setSize(400, 300);
                                        bookingFrame.setLayout(new GridLayout(7, 2, 10, 10));
                                        bookingFrame.setLocationRelativeTo(null);

                                        JLabel venueIdLabel = new JLabel("场地 ID:");
                                        venueIdLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField venueIdField = new JTextField(String.valueOf(venueID));
                                        venueIdField.setEditable(false);
                                        JLabel hallIdLabel = new JLabel("影厅编号:");
                                        hallIdLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField hallIdField = new JTextField(String.valueOf(hallID));
                                        hallIdField.setEditable(false);
                                        JLabel startDateLabel = new JLabel("开始日期 (YYYY-MM-DD):");
                                        startDateLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField startDateField = new JTextField(10);
                                        JLabel startTimeLabel = new JLabel("开始时间 (HH:MM:SS):");
                                        startTimeLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField startTimeField = new JTextField(10);
                                        JLabel endDateLabel = new JLabel("结束日期 (YYYY-MM-DD):");
                                        endDateLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField endDateField = new JTextField(10);
                                        JLabel endTimeLabel = new JLabel("结束时间 (HH:MM:SS):");
                                        endTimeLabel.setFont(new Font("楷书", Font.PLAIN, 16));
                                        JTextField endTimeField = new JTextField(10);

                                        JButton bookButton = new JButton("预订场地");
                                        bookButton.addActionListener(bookEvent -> {
                                            try {
                                                int userID = 1; // 示例：用户 ID
                                                Date startDate = Date.valueOf(startDateField.getText());
                                                Time startTime = Time.valueOf(startTimeField.getText());
                                                Date endDate = Date.valueOf(endDateField.getText());
                                                Time endTime = Time.valueOf(endTimeField.getText());

                                                boolean result = ticketingService.bookVenue(userID, venueID, startDate, startTime, endDate, endTime, hallID);
                                                if (result) {
                                                    JOptionPane.showMessageDialog(null, "场地预订成功！");
                                                    bookingFrame.dispose();
                                                } else {
                                                    JOptionPane.showMessageDialog(null, "该时段场地已被预订，请更换时段。");
                                                }
                                            } catch (NumberFormatException ex) {
                                                JOptionPane.showMessageDialog(null, "输入格式错误，请检查场地 ID 和影厅 ID 是否为数字！");
                                            } catch (Exception ex) {
                                                JOptionPane.showMessageDialog(null, "输入格式错误，请检查日期和时间格式！");
                                            }
                                        });

                                        bookingFrame.add(venueIdLabel);
                                        bookingFrame.add(venueIdField);
                                        bookingFrame.add(hallIdLabel);
                                        bookingFrame.add(hallIdField);
                                        bookingFrame.add(startDateLabel);
                                        bookingFrame.add(startDateField);
                                        bookingFrame.add(startTimeLabel);
                                        bookingFrame.add(startTimeField);
                                        bookingFrame.add(endDateLabel);
                                        bookingFrame.add(endDateField);
                                        bookingFrame.add(endTimeLabel);
                                        bookingFrame.add(endTimeField);
                                        bookingFrame.add(new JLabel()); // 占位
                                        bookingFrame.add(bookButton);
                                        bookingFrame.setVisible(true);
                                    }
                                }
                            });

                            detailsFrame.setVisible(true);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        return functionPanel;
    }

    // 创建活动门票管理主面板
    private static JPanel createEventTicketManagement() {
        JPanel eventTicketPanel = new JPanel(new BorderLayout());
        eventTicketPanel.setBackground(new Color(240, 248, 255));

        // 创建活动门票管理标题标签
        JLabel title = new JLabel("活动门票管理");
        title.setFont(new Font("隶书", Font.PLAIN, 24));
        title.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 创建表格显示活动门票信息
        String[] columnNames = {"ID", "影院名", "影厅名", "预定日期", "开始日期", "开始时间", "结束日期", "结束时间", "票价"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable eventTicketTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(eventTicketTable);

        // 加载数据到表格
        loadEventTicketData(tableModel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton modifyButton = new JButton("修改票价");
        modifyButton.addActionListener(e -> {
            int selectedRow = eventTicketTable.getSelectedRow();
            if (selectedRow != -1) {
                int combinedID = (int) tableModel.getValueAt(selectedRow, 0);
                BigDecimal currentPrice = (BigDecimal) tableModel.getValueAt(selectedRow, 8);

                // 弹出修改票价窗口
                JFrame modifyPriceFrame = new JFrame("修改票价");
                modifyPriceFrame.setSize(300, 200);
                modifyPriceFrame.setLayout(new GridLayout(3, 2, 10, 10));
                modifyPriceFrame.setLocationRelativeTo(null);

                JLabel priceLabel = new JLabel("当前票价:");
                JTextField priceField = new JTextField(currentPrice == null ? "" : currentPrice.toString());
                JButton saveButton = new JButton("保存");

                saveButton.addActionListener(saveEvent -> {
                    try {
                        BigDecimal newPrice = new BigDecimal(priceField.getText());
                        // 更新数据库中的票价
                        try (Connection conn = Conn.getConn()) {
                            String updateSql = "UPDATE MovieVenueBookings SET TicketPrice = ? WHERE ID = ?";
                            try (PreparedStatement pstmt = conn.prepareStatement(updateSql)) {
                                pstmt.setBigDecimal(1, newPrice);
                                pstmt.setInt(2, combinedID);
                                pstmt.executeUpdate();
                                // 更新表格数据
                                tableModel.setValueAt(newPrice, selectedRow, 8);
                                JOptionPane.showMessageDialog(modifyPriceFrame, "票价修改成功");
                                modifyPriceFrame.dispose();
                            }
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(modifyPriceFrame, "修改失败，请稍后重试");
                        }
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(modifyPriceFrame, "请输入有效的票价");
                    }
                });

                modifyPriceFrame.add(priceLabel);
                modifyPriceFrame.add(priceField);
                modifyPriceFrame.add(new JLabel());
                modifyPriceFrame.add(saveButton);
                modifyPriceFrame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(eventTicketPanel, "请选择要修改的活动");
            }
        });

        buttonPanel.add(modifyButton);

        // 将组件添加到主面板
        eventTicketPanel.add(title, BorderLayout.NORTH);
        eventTicketPanel.add(scrollPane, BorderLayout.CENTER);
        eventTicketPanel.add(buttonPanel, BorderLayout.SOUTH);

        return eventTicketPanel; // 返回主面板
    }

//    活动门票  从MovieVenueBookings表获取电影，场地，时间，门票信息
    private static void loadEventTicketData(DefaultTableModel tableModel) {
        tableModel.setRowCount(0); // 清空表格
        try (Connection conn = Conn.getConn()) {
            String sql = "SELECT ID, MovieName,VenueName, HallName, StartDate, StartTime, EndDate, EndTime, TicketPrice FROM MovieVenueBookings";
            try (PreparedStatement pstmt = conn.prepareStatement(sql);
                 ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = {
                            rs.getInt("ID"),
                            rs.getString("MovieName"),
                            rs.getString("VenueName"),
                            rs.getString("HallName"),
                            rs.getDate("StartDate"),
                            rs.getTime("StartTime"),
                            rs.getDate("EndDate"),
                            rs.getTime("EndTime"),
                            rs.getBigDecimal("TicketPrice")
                    };
                    tableModel.addRow(rowData);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    电影票管理  处理退票申请
    private static void handleRefundApplications() {
        JFrame refundFrame = new JFrame("处理退票申请");
        refundFrame.setSize(800, 400); // 适当增大窗口宽度以显示更多信息
        refundFrame.setLayout(new BorderLayout());
        refundFrame.setLocationRelativeTo(null);

        // 从数据库获取退票申请信息
        String[] columnNames = {"订单ID", "电影名称", "影院名称", "影厅名称", "退票理由", "处理状态"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable refundTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(refundTable);

        // 调用 RefundService 获取退票申请信息
        List<RefundApplication> applications = TicketingService.RefundService.getRefundApplications();
        for (RefundApplication application : applications) {
            Object[] rowData = {
                    application.getOrderID(),
                    application.getMovieName(),
                    application.getVenueName(),
                    application.getHallName(),
                    application.getRefundReason(),
                    application.getRefundStatus()
            };
            tableModel.addRow(rowData);
        }

        // 处理按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton approveButton = new JButton("通过");
        JButton rejectButton = new JButton("拒绝");

        // 通过按钮点击事件
        approveButton.addActionListener(e -> {
            int selectedRow = refundTable.getSelectedRow();
            if (selectedRow != -1) {
                int orderID = (int) tableModel.getValueAt(selectedRow, 0);
                String movieName = (String) tableModel.getValueAt(selectedRow, 1);
                String venueName = (String) tableModel.getValueAt(selectedRow, 2);
                String hallName = (String) tableModel.getValueAt(selectedRow, 3);
                if (TicketingService.RefundService.approveRefund(orderID)) {
                    // 更新表格数据
                    tableModel.setValueAt("已退款", selectedRow, 5);
                    JOptionPane.showMessageDialog(refundFrame, "退票申请已通过，订单ID: " + orderID + "，电影: " + movieName + "，影院: " + venueName + "，影厅: " + hallName);
                } else {
                    JOptionPane.showMessageDialog(refundFrame, "处理失败，请稍后重试");
                }
            } else {
                JOptionPane.showMessageDialog(refundFrame, "请选择要处理的退票申请");
            }
        });

        // 拒绝按钮点击事件
        rejectButton.addActionListener(e -> {
            int selectedRow = refundTable.getSelectedRow();
            if (selectedRow != -1) {
                int orderID = (int) tableModel.getValueAt(selectedRow, 0);
                String movieName = (String) tableModel.getValueAt(selectedRow, 1);
                String venueName = (String) tableModel.getValueAt(selectedRow, 2);
                String hallName = (String) tableModel.getValueAt(selectedRow, 3);
                if (TicketingService.RefundService.rejectRefund(orderID)) {
                    // 更新表格数据
                    tableModel.setValueAt("已拒绝", selectedRow, 5);
                    JOptionPane.showMessageDialog(refundFrame, "退票申请已拒绝，订单ID: " + orderID + "，电影: " + movieName + "，影院: " + venueName + "，影厅: " + hallName);
                } else {
                    JOptionPane.showMessageDialog(refundFrame, "处理失败，请稍后重试");
                }
            } else {
                JOptionPane.showMessageDialog(refundFrame, "请选择要处理的退票申请");
            }
        });

        buttonPanel.add(approveButton);
        buttonPanel.add(rejectButton);

        refundFrame.add(scrollPane, BorderLayout.CENTER);
        refundFrame.add(buttonPanel, BorderLayout.SOUTH);
        refundFrame.setVisible(true);
    }

//    电影场地预定，给电影添加场地，时间信息
    private static void movieVenueBooking() {
        JFrame bookingFrame = new JFrame("电影场地预定");
        bookingFrame.setSize(600, 400);
        bookingFrame.setLayout(new BorderLayout());
        bookingFrame.setLocationRelativeTo(null);

        // 从数据库获取所有电影信息，和普通用户票务查询展示的电影信息一样
        String[] columnNames = {"电影ID", "电影名称", "上映年份", "主演", "导演", "编剧"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable movieTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(movieTable);

        // 模拟从数据库获取电影信息
        try (Connection conn = Conn.getConn()) {
            String sql = "SELECT MovieID, MovieName, ReleaseYear, Actors, Director, Screenwriter FROM Movies";
            try (PreparedStatement pstmt = conn.prepareStatement(sql);
                 ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = {
                            rs.getInt("MovieID"),
                            rs.getString("MovieName"),
                            rs.getInt("ReleaseYear"),
                            rs.getString("Actors"),
                            rs.getString("Director"),
                            rs.getString("Screenwriter")
                    };
                    tableModel.addRow(rowData);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 表格点击事件
        movieTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = movieTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 弹出窗口显示场地预定信息
                    JFrame venueBookingFrame = new JFrame("场地预定信息");
                    venueBookingFrame.setSize(600, 400);
                    venueBookingFrame.setLayout(new BorderLayout());
                    venueBookingFrame.setLocationRelativeTo(null);

                    // 从数据库获取场地预定信息（来自场地预定功能录入的数据）
                    String[] venueColumnNames = {"影院名", "影厅名", "预定开始日期", "预定结束日期", "预定开始时间", "预定结束时间"};
                    DefaultTableModel venueTableModel = new DefaultTableModel(venueColumnNames, 0);
                    JTable venueTable = new JTable(venueTableModel);
                    JScrollPane venueScrollPane = new JScrollPane(venueTable);

                    try (Connection conn = Conn.getConn()) {
                        String sql = "SELECT VenueName, HallName, StartDate, EndDate, StartTime, EndTime " +
                                "FROM CombinedVenueBookings";
                        try (PreparedStatement pstmt = conn.prepareStatement(sql);
                             ResultSet rs = pstmt.executeQuery()) {
                            while (rs.next()) {
                                Object[] rowData = {
                                        rs.getString("VenueName"),
                                        rs.getString("HallName"),
                                        rs.getDate("StartDate"),
                                        rs.getDate("EndDate"),
                                        rs.getTime("StartTime"),
                                        rs.getTime("EndTime")
                                };
                                venueTableModel.addRow(rowData);
                            }
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }

                    venueBookingFrame.add(venueScrollPane, BorderLayout.CENTER);

                    // 在弹窗底部添加一个按钮（预定）
                    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                    JButton bookButton = new JButton("预定");
                    bookButton.addActionListener(bookEvent -> {
                        int selectedVenueRow = venueTable.getSelectedRow();
                        if (selectedVenueRow != -1) {
                            String movieName = (String) tableModel.getValueAt(selectedRow, 1);
                            String venueName = (String) venueTableModel.getValueAt(selectedVenueRow, 0);
                            String hallName = (String) venueTableModel.getValueAt(selectedVenueRow, 1);
                            java.sql.Date startDate = (java.sql.Date) venueTableModel.getValueAt(selectedVenueRow, 2);
                            java.sql.Date endDate = (java.sql.Date) venueTableModel.getValueAt(selectedVenueRow, 3);
                            java.sql.Time startTime = (java.sql.Time) venueTableModel.getValueAt(selectedVenueRow, 4);
                            java.sql.Time endTime = (java.sql.Time) venueTableModel.getValueAt(selectedVenueRow, 5);

                            // 将信息插入到新的数据库表中
                            insertIntoNewTable(movieName, venueName, hallName, startDate, endDate, startTime, endTime);

                            // 删除 VenueBookings 和 CombinedVenueBookings 表中的对应数据
                            deleteBookingsFromTables(venueName, hallName, startDate, endDate, startTime, endTime);

                            JOptionPane.showMessageDialog(venueBookingFrame, "预定成功");
                            // 从表格中移除已预定的行
                            venueTableModel.removeRow(selectedVenueRow);
                        } else {
                            JOptionPane.showMessageDialog(venueBookingFrame, "请选择要预定的场地信息");
                        }
                    });
                    buttonPanel.add(bookButton);
                    venueBookingFrame.add(buttonPanel, BorderLayout.SOUTH);

                    venueBookingFrame.setVisible(true);
                }
            }
        });
        bookingFrame.add(scrollPane, BorderLayout.CENTER);
        bookingFrame.setVisible(true);
    }

    // 电影场地预定功能  插入数据到MovieVenueBookings
    private static void insertIntoNewTable(String movieName, String venueName, String hallName,
                                           java.sql.Date startDate, java.sql.Date endDate,
                                           java.sql.Time startTime, java.sql.Time endTime) {
        String sql = "INSERT INTO MovieVenueBookings (MovieName, VenueName, HallName, StartDate, EndDate, StartTime, EndTime, TicketPrice) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; // 增加了 TicketPrice 字段

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, movieName);
            pstmt.setString(2, venueName);
            pstmt.setString(3, hallName);
            pstmt.setDate(4, startDate);
            pstmt.setDate(5, endDate);
            pstmt.setTime(6, startTime);
            pstmt.setTime(7, endTime);
            pstmt.setBigDecimal(8, BigDecimal.ZERO); // 假设默认值为 0，可以根据实际情况修改
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除 VenueBookings 和 CombinedVenueBookings 表中的对应数据
    private static void deleteBookingsFromTables(String venueName, String hallName, java.sql.Date startDate, java.sql.Date endDate, java.sql.Time startTime, java.sql.Time endTime) {
        // 先根据 VenueName 从 Venues 表中获取 VenueID
        int venueId = getVenueIdFromName(venueName);
        if (venueId != -1) {
            try (Connection conn = Conn.getConn()) {
                // 删除 VenueBookings 表中的数据
                String deleteVenueBookingsSql = "DELETE FROM VenueBookings WHERE VenueID = ? AND StartDate = ? AND EndDate = ? AND StartTime = ? AND EndTime = ?";
                try (PreparedStatement pstmtVenueBookings = conn.prepareStatement(deleteVenueBookingsSql)) {
                    pstmtVenueBookings.setInt(1, venueId);
                    pstmtVenueBookings.setDate(2, startDate);
                    pstmtVenueBookings.setDate(3, endDate);
                    pstmtVenueBookings.setTime(4, startTime);
                    pstmtVenueBookings.setTime(5, endTime);
                    pstmtVenueBookings.executeUpdate();
                }

                // 删除 CombinedVenueBookings 表中的数据
                String deleteCombinedVenueBookingsSql = "DELETE FROM CombinedVenueBookings WHERE VenueName = ? AND HallName = ? AND StartDate = ? AND EndDate = ? AND StartTime = ? AND EndTime = ?";
                try (PreparedStatement pstmtCombinedVenueBookings = conn.prepareStatement(deleteCombinedVenueBookingsSql)) {
                    pstmtCombinedVenueBookings.setString(1, venueName);
                    pstmtCombinedVenueBookings.setString(2, hallName);
                    pstmtCombinedVenueBookings.setDate(3, startDate);
                    pstmtCombinedVenueBookings.setDate(4, endDate);
                    pstmtCombinedVenueBookings.setTime(5, startTime);
                    pstmtCombinedVenueBookings.setTime(6, endTime);
                    pstmtCombinedVenueBookings.executeUpdate();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 根据 VenueName 从 Venues 表中获取 VenueID
    private static int getVenueIdFromName(String venueName) {
        int venueId = -1;
        String sql = "SELECT VenueID FROM Venues WHERE VenueName = ?";
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, venueName);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    venueId = rs.getInt("VenueID");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return venueId;
    }

//    电影场次管理
    private static void movieScreeningManagement() {
        JFrame screeningFrame = new JFrame("电影场次管理");
        screeningFrame.setSize(600, 400);
        screeningFrame.setLayout(new BorderLayout());
        screeningFrame.setLocationRelativeTo(null);

        // 从数据库获取电影场次信息，使用 MovieVenueBookings 表
        String[] columnNames = {"ID", "电影名称", "影院名", "影厅名", "开始日期", "结束日期", "开始时间", "结束时间"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable screeningTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(screeningTable);

        // 从数据库获取 MovieVenueBookings 表中的电影场次信息
        try (Connection conn = Conn.getConn()) {
            String sql = "SELECT ID, MovieName, VenueName, HallName, StartDate, EndDate, StartTime, EndTime FROM MovieVenueBookings";
            try (PreparedStatement pstmt = conn.prepareStatement(sql);
                 ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = {
                            rs.getInt("ID"),
                            rs.getString("MovieName"),
                            rs.getString("VenueName"),
                            rs.getString("HallName"),
                            rs.getDate("StartDate"),
                            rs.getDate("EndDate"),
                            rs.getTime("StartTime"),
                            rs.getTime("EndTime")
                    };
                    tableModel.addRow(rowData);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 处理按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton modifyButton = new JButton("修改");
        JButton deleteButton = new JButton("删除");

        // 修改按钮点击事件
        modifyButton.addActionListener(e -> {
            int selectedRow = screeningTable.getSelectedRow();
            if (selectedRow != -1) {
                int id = (int) tableModel.getValueAt(selectedRow, 0);

                // 弹出修改窗口
                JFrame modifyFrame = new JFrame("修改电影场次信息");
                modifyFrame.setSize(400, 300);
                modifyFrame.setLayout(new GridLayout(9, 2, 10, 10));
                modifyFrame.setLocationRelativeTo(null);

                JLabel movieNameLabel = new JLabel("电影名称:");
                JTextField movieNameField = new JTextField((String) tableModel.getValueAt(selectedRow, 1));
                JLabel venueNameLabel = new JLabel("影院名:");
                JTextField venueNameField = new JTextField((String) tableModel.getValueAt(selectedRow, 2));
                JLabel hallNameLabel = new JLabel("影厅名:");
                JTextField hallNameField = new JTextField((String) tableModel.getValueAt(selectedRow, 3));
                JLabel startDateLabel = new JLabel("开始日期 (YYYY-MM-DD):");
                JTextField startDateField = new JTextField(tableModel.getValueAt(selectedRow, 4).toString());
                JLabel endDateLabel = new JLabel("结束日期 (YYYY-MM-DD):");
                JTextField endDateField = new JTextField(tableModel.getValueAt(selectedRow, 5).toString());
                JLabel startTimeLabel = new JLabel("开始时间 (HH:MM:SS):");
                JTextField startTimeField = new JTextField(tableModel.getValueAt(selectedRow, 6).toString());
                JLabel endTimeLabel = new JLabel("结束时间 (HH:MM:SS):");
                JTextField endTimeField = new JTextField(tableModel.getValueAt(selectedRow, 7).toString());

                JButton saveButton = new JButton("保存");
                saveButton.addActionListener(saveEvent -> {
                    try {
                        String movieName = movieNameField.getText();
                        String venueName = venueNameField.getText();
                        String hallName = hallNameField.getText();
                        java.sql.Date startDate = java.sql.Date.valueOf(startDateField.getText());
                        java.sql.Date endDate = java.sql.Date.valueOf(endDateField.getText());
                        java.sql.Time startTime = java.sql.Time.valueOf(startTimeField.getText());
                        java.sql.Time endTime = java.sql.Time.valueOf(endTimeField.getText());

                        // 更新数据库中的电影场次信息
                        try (Connection conn = Conn.getConn()) {
                            String sql = "UPDATE MovieVenueBookings SET MovieName = ?, VenueName = ?, HallName = ?, StartDate = ?, EndDate = ?, StartTime = ?, EndTime = ? WHERE ID = ?";
                            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                                pstmt.setString(1, movieName);
                                pstmt.setString(2, venueName);
                                pstmt.setString(3, hallName);
                                pstmt.setDate(4, startDate);
                                pstmt.setDate(5, endDate);
                                pstmt.setTime(6, startTime);
                                pstmt.setTime(7, endTime);
                                pstmt.setInt(8, id);
                                pstmt.executeUpdate();
                                // 更新表格数据
                                tableModel.setValueAt(movieName, selectedRow, 1);
                                tableModel.setValueAt(venueName, selectedRow, 2);
                                tableModel.setValueAt(hallName, selectedRow, 3);
                                tableModel.setValueAt(startDate, selectedRow, 4);
                                tableModel.setValueAt(endDate, selectedRow, 5);
                                tableModel.setValueAt(startTime, selectedRow, 6);
                                tableModel.setValueAt(endTime, selectedRow, 7);
                                JOptionPane.showMessageDialog(modifyFrame, "电影场次信息修改成功");
                                modifyFrame.dispose();
                            }
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(modifyFrame, "修改失败，请稍后重试");
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(modifyFrame, "输入格式错误，请检查日期和时间格式！");
                    }
                });

                modifyFrame.add(movieNameLabel);
                modifyFrame.add(movieNameField);
                modifyFrame.add(venueNameLabel);
                modifyFrame.add(venueNameField);
                modifyFrame.add(hallNameLabel);
                modifyFrame.add(hallNameField);
                modifyFrame.add(startDateLabel);
                modifyFrame.add(startDateField);
                modifyFrame.add(endDateLabel);
                modifyFrame.add(endDateField);
                modifyFrame.add(startTimeLabel);
                modifyFrame.add(startTimeField);
                modifyFrame.add(endTimeLabel);
                modifyFrame.add(endTimeField);
                modifyFrame.add(new JLabel());
                modifyFrame.add(saveButton);
                modifyFrame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(screeningFrame, "请选择要修改的电影场次");
            }
        });

        // 删除按钮点击事件
        deleteButton.addActionListener(e -> {
            int selectedRow = screeningTable.getSelectedRow();
            if (selectedRow != -1) {
                int id = (int) tableModel.getValueAt(selectedRow, 0);

                int confirm = JOptionPane.showConfirmDialog(screeningFrame, "确定要删除该电影场次吗？", "确认删除",
                        JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 从数据库中删除电影场次信息
                    try (Connection conn = Conn.getConn()) {
                        String sql = "DELETE FROM MovieVenueBookings WHERE ID = ?";
                        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                            pstmt.setInt(1, id);
                            pstmt.executeUpdate();
                            // 从表格中删除该行数据
                            tableModel.removeRow(selectedRow);
                            JOptionPane.showMessageDialog(screeningFrame, "电影场次删除成功");
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(screeningFrame, "删除失败，请稍后重试");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(screeningFrame, "请选择要删除的电影场次");
            }
        });

        buttonPanel.add(modifyButton);
        buttonPanel.add(deleteButton);

        screeningFrame.add(scrollPane, BorderLayout.CENTER);
        screeningFrame.add(buttonPanel, BorderLayout.SOUTH);
        screeningFrame.setVisible(true);
    }
}